package Queue

import "go_example/day01/LinkStack"

type QueueLink struct {
	rear  *LinkStack.Node
	front *LinkStack.Node
}

type LinkQueue interface {
	length() int
	Enqueue(value interface{})
	Dequeue() interface{}
}

func NewLinkQueue() LinkQueue {
	return &QueueLink{}
}

func (ql *QueueLink) length() int {
	pnext := ql.front
	length := 0
	for pnext.Pnext != nil {
		pnext = pnext.Pnext
		length++
	}
	return length
}

//入队
func (ql *QueueLink) Enqueue(value interface{}) {
	newnode:= &LinkStack.Node{value,nil}
	if ql.front == nil{
		ql.front = newnode //插入一个节点
		ql.rear = newnode
	}else{
		ql.rear.Pnext = newnode
		ql.rear = ql.rear.Pnext
	}
}

//出队
func (ql *QueueLink) Dequeue() interface{} {
	if ql.front == nil{
		return nil
	}
	newnode:= ql.front //记录头部位置
	if ql.front == ql.rear{ //只剩下一个
		ql.front = nil
		ql.rear = nil
	}else{
		ql.front = ql.front.Pnext //删除一个
	}

	return newnode.Data
}
